package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.UserConstants;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static com.heima.common.constants.WemediaConstants.*;
import static com.heima.common.constants.WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC;

/**
 * @author JianKang
 * @create 2023-10-20 17:21
 */
@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    WmMaterialMapper wmMaterialMapper;

    @Autowired
    WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    WmNewsTaskService wmNewsTaskService;

    @Autowired
    KafkaTemplate<String, String> kafkaTemplate;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.检查分页参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2.分页
        IPage page = new Page(dto.getPage(), dto.getSize());
        //3.获取当前用户ID
        Integer userId = WmThreadLocalUtil.getUser().getId();
        //4.条件查询
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNews::getUserId, userId);
        //根据status查询
        Short status = dto.getStatus();
        if (status != null) {
            queryWrapper.eq(WmNews::getStatus, status);
        }
        //按频道查询
        Integer channelId = dto.getChannelId();
        if (channelId != null) {
            queryWrapper.eq(WmNews::getChannelId, channelId);
        }
        //按时间查询
        Date beginPubDate = dto.getBeginPubDate();
        Date endPubDate = dto.getEndPubDate();
        if (beginPubDate != null && endPubDate != null) {
            queryWrapper.between(WmNews::getCreatedTime, beginPubDate, endPubDate);
        }
        //按关键词查询
        String keyword = dto.getKeyword();
        if (keyword != null) {
            queryWrapper.like(WmNews::getTitle, keyword);
        }
        //按发布时间倒序查询
        queryWrapper.orderByDesc(WmNews::getCreatedTime);
        page = page(page, queryWrapper);
        //5.返回结果
        List<WmNews> records = page.getRecords();
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(records);
        return result;
    }

    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //0.条件判断
        if (dto == null || dto.getContent() == null || dto.getContent().isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.保存或修改文章
        WmNews wmNews = new WmNews();
        //属性拷贝
        BeanUtils.copyProperties(dto, wmNews);
        if (dto.getImages() != null && !dto.getImages().isEmpty()) {
            wmNews.setImages(StringUtils.join(dto.getImages(), ","));
        }
        //封面属性为自动
        if (dto.getType().equals(WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        saveOrUpdateWmNews(wmNews);
        //2.判断是否是草稿，是则结束当前方法
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //3.不是草稿，保存文章内容图片与素材的关系
        //获取文章图片URL
        List<String> imgUrls = ectractUrlInfo(dto.getContent());
        //保存文章内容图片与素材的关系
        saveRelativeInfoForContent(imgUrls, wmNews.getId());
        //保存文章封面图片与素材的关系
        saveRelativeInfoForCover(dto, wmNews, imgUrls);
        //审核文章
//        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        wmNewsTaskService.addNewsToTask(wmNews.getId(), wmNews.getPublishTime());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult getOneNew(Integer newsId) {
        if (newsId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, newsId));
        if (wmNews != null) {
            return ResponseResult.okResult(wmNews);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto wmNewsDto) {
        //0.检查参数
        if (wmNewsDto == null || wmNewsDto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章ID不可缺少");
        }
        Integer newsId = wmNewsDto.getId();
        //1.查询文章
        WmNews wmNews = getById(newsId);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //2.查询是否是发布状态
        if (wmNews.getStatus() != WmNews.Status.PUBLISHED.getCode()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布状态，不能上下架");
        }
        //3.修改文章enable
        if (wmNewsDto.getEnable() != null && wmNewsDto.getEnable() > -1 && wmNewsDto.getEnable() < 2) {
            boolean success = update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable, wmNewsDto.getEnable())
                    .eq(WmNews::getId, wmNews.getId()));
            if (success) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("articleId", wmNews.getArticleId());
                map.put("enable", wmNewsDto.getEnable());
                kafkaTemplate.send(WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult delNews(Integer newsId) {
        //0.检查参数
        if (newsId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章ID不可缺少");
        }
        //1.检查文章是否存在
        WmNews wmNews = getById(newsId);
        //2.不存在直接返回
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章信息不存在");
        }
        //3.检查文章是否已经发布
        if (wmNews.getStatus() == WmNews.Status.PUBLISHED.getCode()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章已发布，不能删除");
        }
        //4.存在则查找与文章关联的素材id
        List<Integer> wmNewsMaterialIds = wmNewsMaterialMapper.selectList(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, newsId)).stream().map(WmNewsMaterial::getId).collect(Collectors.toList());
        //5.删除与文章关联的素材信息
        if (!wmNewsMaterialIds.isEmpty()) {
            wmNewsMaterialMapper.deleteBatchIds(wmNewsMaterialIds);
        }
        //6.删除文章
        this.removeById(newsId);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult listVo(NewsAuthDto dto) {
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2.创建分页参数
        IPage page = new Page(dto.getPage(), dto.getSize());
        //3.创建条件查询
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        if (dto.getTitle() != null) {
            queryWrapper.like(WmNews::getTitle, dto.getTitle());
        }
        page = page(page, queryWrapper);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    @Override
    public ResponseResult oneVo(Integer id) {
        //1.检查参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        return ResponseResult.okResult(getById(id));
    }

    @Override
    public ResponseResult authFail(NewsAuthDto dto) {
        //1.检查参数
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.修改用户审核信息
        WmNews wmNews = new WmNews();
        wmNews.setId(dto.getId());
        if (dto.getMsg() != null && StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        //2.1设置审核失败
        wmNews.setStatus(WmNews.Status.FAIL.getCode());
        if (updateById(wmNews)) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "更新失败，请重试");
    }

    @Override
    public ResponseResult authPass(NewsAuthDto dto) {
        //1.检查参数
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.修改用户审核信息
        WmNews wmNews = new WmNews();
        wmNews.setId(dto.getId());
        if (dto.getMsg() != null && StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        //2.1设置审核失败
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        if (updateById(wmNews)) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "更新失败，请重试");
    }


    /**
     * 第一个功能：如果当前封面类型为自动，则设置封面类型的数据
     * 匹配规则：
     * 1，如果内容图片大于等于1，小于3  单图  type 1
     * 2，如果内容图片大于等于3  多图  type 3
     * 3，如果内容没有图片，无图  type 0
     * <p>
     * 第二个功能：保存封面图片与素材的关系
     *
     * @param dto
     * @param wmNews
     * @param imgUrls
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> imgUrls) {
        List<String> images = dto.getImages();
        //自动模式
        if (dto.getType().equals(WM_NEWS_TYPE_AUTO)) {
            //无图模式
            if (imgUrls.isEmpty()) {
                wmNews.setType(WM_NEWS_NONE_IMAGE);
            } else if (imgUrls.size() < 3) {
                //单图模式
                wmNews.setType(WM_NEWS_SINGLE_IMAGE);
                images = imgUrls.stream().limit(1).collect(Collectors.toList());
            } else {
                //多图模式
                wmNews.setType(WM_NEWS_MANY_IMAGE);
                images = imgUrls.stream().limit(3).collect(Collectors.toList());
            }
            //修改文章
            if (images != null && !images.isEmpty()) {
                wmNews.setImages(StringUtils.join(images, ","));
            }
            updateById(wmNews);
        }
        if (images != null && !images.isEmpty()) {
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        }
    }

    /**
     * 处理文章内容图片与素材的关系
     *
     * @param materials
     * @param newsId
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }


    /**
     * 保存文章图片与素材的关系到数据库中
     *
     * @param materials
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        if (materials != null && !materials.isEmpty()) {
            //通过图片的url查询素材的id
            List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));

            //判断素材是否有效
            if (dbMaterials == null || dbMaterials.isEmpty()) {
                //手动抛出异常   第一个功能：能够提示调用者素材失效了，第二个功能，进行数据的回滚
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }

            if (materials.size() != dbMaterials.size()) {
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }

            List<Integer> idList = dbMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

            //批量保存
            wmNewsMaterialMapper.saveRelations(idList, newsId, type);
        }

    }


    /**
     * 提取文章内容中的图片信息
     *
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<String> materials = new ArrayList<>();

        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                String imgUrl = (String) map.get("value");
                materials.add(imgUrl);
            }
        }

        return materials;
    }

    /**
     * 保存或修改文章
     *
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        //补全属性
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);//默认上架

        if (wmNews.getId() == null) {
            //保存
            save(wmNews);
        } else {
            //修改
            //删除文章图片与素材的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }

    }
}
